package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import model.UserInfo;
import util.AppVar;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet("/getuserbyaid")
public class GetUserByAld extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "未知错误！";
        UserInfo userInfo = new UserInfo();
        // 1. 得到前端的参数并效验
        String aidStr = req.getParameter("aid");
        if(!StrUtil.isBlank(aidStr)) {
            int aid = Integer.valueOf(aidStr);
            if(aid > 0) {
                // 2.查询数据库，并组织返回的数据
                Connection connection = DBUtils.getConnection();
                // 查询用户信息
                String sql = "select * from userinfo where uid=(select uid from article where aid=?)";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setInt(1, aid);
                ResultSet resultSet = statement.executeQuery();
                if(resultSet.next()) {
                    userInfo.setUid(resultSet.getInt("uid"));
                    userInfo.setUsername(resultSet.getString("username"));
                    userInfo.setImg(resultSet.getString("img"));
                }
                // 查询出用户发表的所有文章数
                sql = "select count(*) as acount from article where uid=(select uid from article where aid=?)";
                PreparedStatement statement2 = connection.prepareStatement(sql);
                statement2.setInt(1, aid);
                ResultSet resultSet2 = statement2.executeQuery();
                if(resultSet2.next()) {
                    userInfo.setAcount(resultSet2.getInt("acount"));
                }
                msg = "";
                // 关闭资源
                DBUtils.close(resultSet2,statement2, null);
                DBUtils.close(resultSet, statement, connection);
            }else {
                msg = "非法参数！";
            }
        }else {
            msg = "非法参数！";
        }
        // 3. 将上面查询的数据，返回给前端
        resp.setContentType(AppVar.RESPONSE_CONTENTTYPE_JSON);
        resp.getWriter().println(
                JSONUtil.toJsonStr(ResultUtils.toResult(200, userInfo, msg))
        );
    }
}










